package gr.atc.epart;

import java.util.ArrayList;

import gr.atc.epart.actions.Deliberation;
import gr.atc.epart.googlewrapper.GoogleServiceCallbackType;
import gr.atc.epart.googlewrapper.accounts.GoogleLoginDialog;
import gr.atc.epart.googlewrapper.moderator.GoogleModerator;
import gr.atc.epart.googlewrapper.moderator.ModeratorSeries;
import gr.atc.epart.googlewrapper.moderator.ModeratorSubmission;
import gr.atc.epart.googlewrapper.moderator.ModeratorTopic;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

public class DeliberationSubmissionActivity extends ListActivity {
	private final static int ADD_SUBMISSION = 0;
	private DeliberationSubmissionAdapter _adapter;
	private ProgressDialog _progressDialog;
	private GoogleModerator _moderator;
	private ModeratorTopic _topic;
	ArrayList<ModeratorSubmission> _submissions = new ArrayList<ModeratorSubmission>();
	//
	// used to receive callbacks
	//
	private Handler _messageHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case GoogleServiceCallbackType.ModeratorSubmissionVoteAdded:

				// update
				showVoteAddedMessage();

				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				_submissions.clear();

				_moderator.getTopicSubmissions(_topic);

				_submissions = _topic.getSubmissionList();

				_adapter.setSubmisions(_submissions);

				// _submissions = _topic.getSubmissionList();
				_adapter.notifyDataSetChanged();

				// update end

				break;

			case GoogleServiceCallbackType.OperationError: {
				if (msg.getData() != null) {
					String error = msg.getData().getString("DESCRIPTION");
					showErrorAlert("Google moderator error:" + error);
					
				}
				dismissProgessDialog();
			}
				break;
			}
		}
	};

//	@Override
//	public void onRestart() {

		// super.onRestart();
		// _submissions.clear();
		// _moderator.getTopicSubmissions(_topic);
		// _submissions = _topic.getSubmissionList();
		// _adapter.setSubmisions(_submissions);
		// _adapter.notifyDataSetChanged();
//	}

	@Override
	public void onCreate(Bundle icicle) {

		super.onCreate(icicle);
		setContentView(R.layout.topicsubmissionslist);

		//
		// there is an serious issue with moderator. It still cannot work with
		// the AccountManager's tokens
		// and authentication is performed through ClientLogin
		// this means that we cannot neither create multiple instances (because
		// each one needs to go through the authentication phase
		// to retrieve the token) nor re-use the same instance because the event
		// handler belongs to another activity.
		//
		// a work around is to create new instances and share the token ASSUMING
		// that it is still valid
		//
		_moderator = new GoogleModerator(_messageHandler);
		_moderator.setAuthToken(EPartVolatileDataStore.getInstance()
				.getModeratorAuthToken());

		EPartVolatileDataStore.getInstance().setModeratorInstance(_moderator);

		_topic = EPartVolatileDataStore.getInstance().getModeratorTopic();

		_submissions = _topic.getSubmissionList();
		// the topics are not available yet....
		_adapter = new DeliberationSubmissionAdapter(this, _submissions);

		setListAdapter(_adapter);

	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(Menu.NONE, ADD_SUBMISSION, Menu.NONE, "Add Opinion");

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {

		case ADD_SUBMISSION:

			Intent viewDeliberationsTopicsIntent = new Intent();
			viewDeliberationsTopicsIntent.setClassName("gr.atc.epart",
					"gr.atc.epart.DeliberationAddSubmissionActivity");
			startActivityForResult(viewDeliberationsTopicsIntent,
					ADD_SUBMISSION/* code is not important */);
			return true;

		default:
			return false;
		}

	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (resultCode) {
		case Activity.RESULT_OK:
			if (requestCode == ADD_SUBMISSION) {
				// a new submission was made
				// Although the response is parsed to a new submission object,
				// I cannot pass it back to this activity...
				// so,I can only retrieve again the submissions of the curren
				// topic in order to update the list
				// stupid, but it is my only way at the moment

				// NOTE : this call is NOT asynchronous...
				// NOTE2: this method was initially intended to append
				// submissions
				// so in our case we need to first remove all the submissions
				// from the topic
				// _topic.getSubmissionList().clear();
				try {
					_topic.removeAllSubmissions();

					showProgressDialog();

					_moderator.getTopicSubmissions(_topic);
					_adapter.setSubmisions(_topic.getSubmissionList());

					dismissProgessDialog();

				} catch (Exception e) {

					Log.i("DeliberationSubmissionActivity", e.getMessage());

				}
			}
			break;
		/*
		 * 
		 * // TODO:: is this activity is called for result, we can pass back the
		 * // new submission, and updte the list locally
		 * 
		 * // I cannot make it work.... // the list should be refreshed...by
		 * retrieving all the data
		 * 
		 * Bundle b = data.getExtras(); ArrayList<ModeratorSubmission>
		 * newsubmissions =
		 * (ArrayList<ModeratorSubmission>)b.getSerializable("NEWSUBMISSION");
		 * ArrayList<ModeratorSubmission> newsubmissions2 =
		 * (ArrayList<ModeratorSubmission>)b.getSerializable("SUBMISSION");
		 * 
		 * //ArrayList<ModeratorSubmission> newsubmissions =
		 * (ArrayList<ModeratorSubmission
		 * >)data.getBundleExtra("NEWSUBMISSION").getSerializable("SUBMISSION");
		 * 
		 * if (newsubmissions.size()>0) { // add all new submissions for local
		 * use for(ModeratorSubmission submission:newsubmissions)
		 * _topic.addSubmission(submission);
		 * 
		 * // update view _adapter.setSubmisions(_topic.getSubmissionList());
		 * _adapter.notifyDataSetChanged(); }
		 */

		default:
			break;
		}
	}

	private void showVoteAddedMessage() {
		Toast.makeText(getBaseContext(), "Your vote was submitted!",
				Toast.LENGTH_LONG).show();
	}

	private void showProgressDialog() {

		_progressDialog = new ProgressDialog(this);
		_progressDialog.setMessage("Please wait...");
		_progressDialog.setIndeterminate(true);
		_progressDialog.setCancelable(false);
		_progressDialog.show();
	}

	private void dismissProgessDialog() {
		_progressDialogHandler.sendEmptyMessage(0);
	}

	// Define the Handler that receives messages from the thread and update the
	// progress
	final Handler _progressDialogHandler = new Handler() {
		public void handleMessage(Message msg) {
			if (_progressDialog != null)
				_progressDialog.dismiss();

		}
	};

	public void showErrorAlert(String msg) {

		AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
		dlgAlert.setMessage(msg);
		dlgAlert.setTitle("Error");
		dlgAlert.setPositiveButton("OK", null);
		dlgAlert.setCancelable(true);
		dlgAlert.create();
		dlgAlert.show();
	}

}
